package uk.ac.ebi.pride.tools.pap.db;

import org.apache.log4j.Logger;

import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;

/**
 * @author Richard Cote
 * @author Florian Reisinger
 *         Date: 17-Feb-2009
 * @since 0.1
 */
public class TomcatManagedOracleConnectionFactory implements ConnectionProvider {

    private static final Logger log = Logger.getLogger(TomcatManagedOracleConnectionFactory.class);

    private DataSource papSource = null;

    private static final TomcatManagedOracleConnectionFactory instance = new TomcatManagedOracleConnectionFactory();

    private TomcatManagedOracleConnectionFactory(){
        // Get the DataSource
        if (papSource == null) {
            try {
                Context context = (Context) (new InitialContext()).lookup("java:comp/env");
                papSource = (DataSource) context.lookup("jdbc/ols");
            } catch (NamingException e) {
                throw new IllegalStateException("OLS JNDI datasource not configured: " + e.getMessage());
            }
        }

        try {
            Connection connection = papSource.getConnection();
            // gets driver info:
            DatabaseMetaData meta = connection.getMetaData();
            log.info("OLS JDBC driver name is " + meta.getDriverName());
            log.info("OLS JDBC driver version is " + meta.getDriverVersion());
            connection.close();
        } catch (SQLException e) {
            throw new IllegalStateException("Could not get connection to test PooledConnectionFactory initialization", e);
        }
    }

    public static TomcatManagedOracleConnectionFactory getInstance() {
        return instance;
    }

    public Connection getConnection() throws SQLException {

        // Retrieve a Connection.
        return papSource.getConnection();

    }

}